読者です 読者をやめる 読者になる 読者になる

liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのUI - BaseAdapterでListView作成

 

activity_main.xml
 
<?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:orientation="vertical">

<ListView
android:id="@+id/myList"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
 
 
MainActivity.java
package com.example.liguofeng.baseadapter;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView listView = (ListView) findViewById(R.id.myList);

// BaseAdapter
BaseAdapter baseAdapter = new BaseAdapter() {
@Override
public int getCount() {
// 20項目
return 20;
}

//
@Override
public Object getItem(int position) {
//
return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Layout生成
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);

ImageView image = new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher);

TextView textView = new TextView(MainActivity.this);
textView.setText("第" + position + "項目");
textView.setTextSize(20);
textView.setTextColor(Color.RED);

layout.addView(image);
layout.addView(textView);

return layout;
}
};

listView.setAdapter(baseAdapter);
}
}