私はデータベースからテキストを取得し、行数がそのデータベース上のテキスト数に依存するテーブルとして表示するAndroidアプリケーションを作成しています。各テキストは行に表示され、その横に共有ボタンが表示されます
2つのレイアウトを作成しました。1つはテーブル用、もう1つは各行用です。各行に関数addtablerowを入力しますが、正確な行の各ボタンを識別するにはどうすればよいですか?
最後のボタンだけがうまく機能し、他のボタンは何のアクションもありませんか?ボタンの配列を作成することを考えましたが、作成時に常にクラッシュします!
詳細については、ここに私のコードがあります
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:layout_height="wrap_content"
android:layout_width="fill_parent" >
<TableLayout
android:id="@+id/my_table"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:stretchColumns="1"
android:shrinkColumns="1"/>
</ScrollView>
table_row_item.xml
<?xml version="1.0" encoding="UTF-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:focusable="true"
android:focusableInTouchMode="false"
android:clickable="true"
android:background="@android:drawable/list_selector_background">
<TextView
android:id="@+id/cell"
/>
<Button
android:id="@+id/button1"
android:layout_width="7dp"
android:layout_height="77dp"
android:text="Button" />
</TableRow>
MainActivity.java
package com.example.tabletest.test;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends Activity {
public int i;
public Button btn;
public TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i=1; //just for test , but later i will get position of data on db
addTableRow();
i=2;
addTableRow();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int j=btn.getId();
Intent sharingIntent = new Intent(
android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "this is"+j;
sharingIntent
.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via: "));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void addTableRow() {
final TableLayout table = (TableLayout) findViewById(R.id.my_table);
final TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.table_row_item, null);
// fill cell txt
tv = (TextView) tr.findViewById(R.id.cell);
tv.setText("This is row"+i);
table.addView(tr);
btn=(Button) tr.findViewById(R.id.button1);
btn.setId(i);
registerForContextMenu(tr);
}
}