当前位置: 代码迷 >> Android >> 无法在GridView项目中设置TextView和自定义背景
  详细解决方案

无法在GridView项目中设置TextView和自定义背景

热度:93   发布时间:2023-08-04 12:11:47.0

我正在开发一个带有10个imageButtons的gridview的应用程序。现在我实现了一个名为SquareImageView的方法,以将列数调整为2,而与屏幕大小无关。我不知道如何将文本放入其中。

我目前的申请是这样的:

如您所见,网格中只有图像。我想给边框,中间每个图像中的一些文本。

我的文件是:

package com.defcomdevs.invento16;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout; 
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBarDrawerToggle;
 import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
 import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
 import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private CollapsingToolbarLayout mcollapsingToolbar;
private NestedScrollView mnestedScrollView;
private CoordinatorLayout coordinatorLayout;
private DrawerLayout drawerLayout;
int backButtonCount = 0;
private Button button;
GridView mygrid;
private ImageButton imageButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
    coordinatorLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
    // drawerLayout.setBackground(getResources().getDrawable(R.drawable.oppo));
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //button= (Button) findViewById(R.id.setalarm);
    mcollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    //mnestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
    mcollapsingToolbar.setTitle("INVENTO '16");
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            callRegister();
        }
    });
    mygrid= (GridView) findViewById(R.id.gridView);
    mygrid.setAdapter(new MizAdapter(this));
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

public void callRegister() {
    Intent intent = new Intent(this, Registration.class);
    startActivity(intent);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }
    if (backButtonCount >= 1) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    } else {
        Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
        backButtonCount++;
    }

}
   /* public void setalarm(View view){
    if(view.getId()==R.id.setalarm){
        Intent intent=new Intent(this,AlarmActivity.class);
        startActivity(intent);
    }
}*/

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent intent = new Intent(this, Settings.class);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.about_college) {
        // Handle the camera action
    } else if (id == R.id.cse) {

    } else if (id == R.id.it) {

    } else if (id == R.id.ece) {

    } else if (id == R.id.mech) {

    } else if (id == R.id.Coding) {
        Intent intent = new Intent(this, Coding.class);
        startActivity(intent);
    } else if (id == R.id.Hacking) {

    } else if (id == R.id.printing) {

    } else if (id == R.id.Big) {

    } else if (id == R.id.nand) {

    } else if (id == R.id.cryo) {

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
class itemName{     //Since we have to bounr the image to the item with the name and the subtitle
                    //we keep all information inside the class and deal with the class entirely
    String Iname;
    int ImageId;
    itemName(String name,int imageId){
        Iname=name;
        ImageId=imageId;
    }
}

class MizAdapter extends BaseAdapter{

    ArrayList<itemName> items;
    Context context;

    MizAdapter(Context context){
        this.context=context;
        items=new ArrayList<itemName>();    //initialize each item with the type itemName.
        Resources res=context.getResources();
        String[] itemnames=res.getStringArray(R.array.Items);
        int[] itempics={R.drawable.hackbttn100,R.drawable.hackbttn100,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn,R.drawable.hackbttn};
        for(int i=0;i<10;i++){
            itemName names=new itemName(itemnames[i],itempics[i]);
            items.add(names);
        }
    }
    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder{
        ImageButton myImage;
        ViewHolder(View v){
            myImage= (ImageButton) v.findViewById(R.id.picture);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row=convertView;
        ViewHolder viewHolder=null;
        if (row==null){
            LayoutInflater inflater= (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
            row=inflater.inflate(R.layout.singleitem, parent, false);
            viewHolder=new ViewHolder(row);
            row.setTag(viewHolder);
        }
        else {
            viewHolder= (ViewHolder) row.getTag();
        }
        itemName temp=items.get(position);
        viewHolder.myImage.setImageResource(temp.ImageId);
        return row;
    }
    public void coding(View v){

    }
}

}接下来是将列数设置为2,而不考虑屏幕大小。

   package com.defcomdevs.invento16;

  import android.content.Context;
  import android.util.AttributeSet;
  import android.widget.ImageButton;

 /**
  * Created by midhun on 23/10/15.
 */
public class SquareImageView extends ImageButton {

public SquareImageView(Context context) {
    super(context);
}

public SquareImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}

我的mainactivity.xml文件

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:id="@+id/app_bar"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="196dp"
        android:background="#3f51b5"
        app:contentScrim="@color/colorPrimary"
        app:expandedTitleMarginEnd="64dp"
        app:expandedTitleMarginStart="48dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">


        <ImageView
            android:id="@+id/imageview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/index"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.widget.NestedScrollView>
<GridView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="1dp"
    android:layout_marginRight="1dp"
    android:layout_marginTop="198dp"
    android:id="@+id/gridView"
    android:verticalSpacing="1dp"
    android:horizontalSpacing="1dp"
    android:numColumns="2"
    android:stretchMode="columnWidth"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

现在,每个ImageButton都有一个通用的布局xml文件

 <?xml version="1.0" encoding="utf-8"?>

<com.defcomdevs.invento16.SquareImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    android:onClick="coding"
    android:background="@drawable/custom_button"/>

同样在这里,我想为所有这些imagebutton定义一个自定义背景,以便当用户单击该按钮时,下面的图像上会出现一点透明的颜色(任何颜色)。 请帮帮我。

为什么不对网格视图布局使用单独的布局。 这样每个按钮实际上都是具有父布局的布局,即RelativeLayout和在布局内部,您有两个子视图。 一种是在底部具有重力参数的文本视图。 然后将图片作为父布局的背景。

使用此布局作为适配器布局。 它将为您想要的每个项目重新创建它。