【发布时间】:2018-10-17 19:51:56
【问题描述】:
我目前正在制作具有自定义布局的基本网格视图。虽然我现在只在 gridview 中显示文本。我在网上遵循一些教程并一步一步地遵循一切,我没有从 android studio 得到任何错误,我运行它。但是当我运行它时,它只显示一个空白的白页。这次我确实初始化了适配器,但它仍然没有显示任何内容。帮助我错过了什么。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/firsttext"
android:layout_width="match_parent"
android:layout_height="@dimen/ButtonSize"
android:text="@string/hello"
android:gravity="center"/>
<GridView
android:layout_below="@+id/firsttext"
android:id="@+id/firstList"
android:layout_width="match_parent"
android:layout_height="200dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth">
</GridView>
</RelativeLayout>
gridlist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/gridtext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello"
android:textSize="@dimen/ButtonSize" />
</RelativeLayout>
gridadapter.java
public class gridAdapter extends BaseAdapter {
Context context;
String[] names;
LayoutInflater layoutInflater;
public gridAdapter(Context context,String[] names) {
this.context = context;
this.names = names;
}
@Override
public int getCount() {
return names.length;
}
@Override
public Object getItem(int position) {
return names[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if (convertView != null){
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = layoutInflater.inflate(R.layout.gridlist,null);
}
TextView textView = (TextView)gridView.findViewById(R.id.gridtext);
textView.setText(names[position]);
return gridView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
String[] Names = {"great","good","average","great","good","average","great","good","average","great","good","average","great","good","average","great","good","average"};
GridView grid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid = (GridView)findViewById(R.id.firstList);
gridAdapter adapter = new gridAdapter(this,Names);
grid.setAdapter(adapter);
}
}
【问题讨论】: