我正在創建自定義網格。每行有1個按鈕和2個文字瀏覽。我試圖以編程方式爲每個值分配值/文本。我可以爲兩個文本視圖設置文本,但是,findviewbyId
對於按鈕返回null。網格佈局中的按鈕爲空
電網是這樣的:
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dip"
android:horizontalSpacing="10dip"
android:stretchMode="columnWidth"
android:gravity="center"
android:background="#FFFFFF"
android:padding="5dip"
android:id="@+id/gvMYActivitySearch" />
行佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button
android:id="@+id/btnHistory"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:background="@drawable/button_background"
android:text="History"/>
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="35dp" />
<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="35dp" />
</LinearLayout>
自定義網格的java文件就像
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] names;
private final String[] Contact;
private final String[] ID;
public CustomGrid(Context c,String[] names,String[] Contact, String[] ID) {
mContext = c;
this.Contact = Contact;
this.names = names;
this.ID = ID;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//grid = new View(mContext);
grid = inflater.inflate(R.layout.myactivity_singlerow, null);
} else {
grid = (View) convertView;
}
TextView tvName = (TextView) grid.findViewById(R.id.tvName);
TextView tvContact = (TextView) grid.findViewById(R.id.tvContact);
Button btnHistory = (Button) grid.findViewById(R.id.btnHistory);
tvName.setText(names[position]);
tvContact.setText(Contact[position]);
if(btnHistory!=null) {
btnHistory.setId(Integer.parseInt(ID[position]));
btnHistory.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
new MainActivity().testButton(view.getId());
}
}
);
}
return grid;
}
當我嘗試調試,我可以看到第一當位置爲'0'時,btnHistory不爲空。但之後,當位置爲1時,btnHistory爲空。
什麼可能會出錯?當兩個textviews都不爲null時,爲什麼btnHistory爲null?
您是否嘗試過使用ViewHolder模式或清潔及重建應用程序? –
您是否將您的適配器設置爲您的gridview? – Chisko
您可能還想嘗試在'getItem()'返回名稱[位置]'' – Chisko