我正在尝试编写自己的习惯View,但我遇到了问题LayoutParams.
想法是扩展ViewGroup(LinearLayout)
public class MyView extends LinearLayout{
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
}
public void putContent(){
setOrientation(HORIZONTAL);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 5; i++){
View view = inflater.inflate(R.layout.item, null);
TextView tv = (TextView)view.findViewById(R.id.item_text);
tv.setText("Item " + i);
addView(view);
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,putContent方法会使项目膨胀并添加到我的视图中.这是一个项目布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<TextView android:text="TextView"
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" …Run Code Online (Sandbox Code Playgroud) 我在关于GridView的android教程中遵循了这个例子,但是我想要使用TextView简单地显示一些文本,而不是显示图像.结果似乎比我想象的更难.看起来这似乎是完全没必要的,它没有一个有效的用例,但我正在尝试这个让自己熟悉sdk.
所以我的代码与http://developer.android.com/guide/tutorials/views/hello-gridview.html中的GridView示例非常相似,但是我没有使用ImageAdapter,而是创建了一个虚拟适配器,如下所示:
public class MyAdapter extends BaseAdapter {
private Context context;
private String[] texts = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "eee", "hhh", "iii"};
public MyAdapter(Context context) {
this.context = context;
}
public int getCount() {
return 9;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(85, 85)); …Run Code Online (Sandbox Code Playgroud)