I have literally tried most solutions on adding rows to a blank TableLayout from code; I still get a blank screen.
Below is the code:
public void updateTable(){
bodyTable.removeViews(ROW_OFFSET, bodyTable.getChildCount() - ROW_OFFSET);
for(int row = 0; row < adapter.getRowCount(); row++){
final int rrow = getRealRowOf(row);
TableRow bodyRow = new TableRow(context);
padColStart(bodyTable, bodyRow);
for(int col = 0; col < adapter.getColumnCount(); col++){
final int rcol = getRealColOf(col);
final boolean expandCol = adapter.isColumnExpandable(col);
bodyTable.setColumnStretchable(rcol, expandCol);
TextView bodyText;
if(adapter.isCellEditable(row, col)){
bodyText = new EditText(context);
bodyText.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
}else
bodyText = new TextView(context);
setBodyText(bodyText, adapter.getValueAt(row, col).toString());
bodyText.setLayoutParams(getRowLayoutParams());
bodyRow.addView(bodyText/*, rcol*/);
addColumnLine(bodyTable, bodyRow, rcol);
}
bodyRow.setLayoutParams(getRowLayoutParams());
bodyTable.addView(bodyRow/*, rrow*/, getTableLayoutParams());
addRowLine(bodyTable, rrow);
}
}
Below adds vertical cell lines:
private void addColumnLine(TableLayout bodyTable, TableRow bodyRow, int rcol){
for(int col_pad = 1; col_pad < COLUMN_STEP; col_pad++){
View view = getColumnLine();
view.setLayoutParams(getColumnLineLayout());
bodyTable.setColumnStretchable(rcol + col_pad, false);
bodyRow.addView(view/* rcol + col_pad,*/);
}
}
private View getColumnLine(){
View colLine = new View(context);
colLine.setBackgroundColor(0x000000);
return colLine;
}
LayoutParams for vertical cell lines
private TableRow.LayoutParams getColumnLineLayout(){
return new TableRow.LayoutParams(getPxFromDp(2), TableRow.LayoutParams.MATCH_PARENT);
}
below adds horizontal row lines:
private void addRowLine(TableLayout bodyTable, int rrow){
for(int row_pad = 1; row_pad < ROW_STEP; row_pad++){
View view = getRowLine();
view.setLayoutParams(getRowLineLayout());
bodyTable.addView(view/* rrow + row_pad,*/, getTableLayoutParams());
}
}
private View getRowLine(){
View rowLine = new View(context);
rowLine.setBackgroundColor(0x000000);
return rowLine;
}
LayoutParams for row lines:
private TableRow.LayoutParams getRowLineLayout(){
return new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, getPxFromDp(2));
}
LayoutParams to add to TableRow:
private TableRow.LayoutParams getRowLayoutParams(){
return new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
}
LayoutParams to add to TableLayout:
private TableLayout.LayoutParams getTableLayoutParams(){
return new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
}
Related
I want to make view by adding child list on android using cardview in recycleview.
i have made class to store these item and make arraylist on each parent of object if the object have child item, so i can differentiate if the list has child or not.
But i have difficulties to render the same layout to make the child list below the parent list. I am pragmatically make the layout one by one but it will be difficult to make that. So i want to render the same layout to my adapter when i want to make a child list whenever the object/class has arraylist of child list in that object.
this is my adapter right now
public class NotificationListAdapter extends BaseListAdapter<NotificationData, NotificationListAdapter.CustomViewHolder> {
private List<NotificationData> notificationData;
private ArrayList<Integer> indexForHide;
public NotificationListAdapter(Context context) {
super(context);
}
#Override
public void addAll(List<NotificationData> items) {
super.addAll(items);
this.notificationData = items;
}
void setChildNotif(){
ArrayList<NotificationData> childDataItems;
List<NotificationData> notificationDataChild = new ArrayList<NotificationData>();
notificationDataChild.addAll(notificationData);
indexForHide = new ArrayList<Integer>();
for (int i = 0; i < notificationData.size(); i++) {
childDataItems = new ArrayList<>();
if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}
for (int j = i; j < notificationDataChild.size(); j++){
if(i==j){
continue;
}else if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}else{
if(notificationDataChild.get(j).getRfqId()!=0){
if(notificationDataChild.get(j).getRfqId()==notificationData.get(i).getRfqId()){
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
if(!notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase("")) {
if (notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase(notificationData.get(i).getInvoiceNumber())) {
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
}
}
notificationData.get(i).setChildNotification(childDataItems);
Log.d("sizeNotif", i+" :"+notificationData.get(i).getChildNotification().size());
}
Log.d("sizeNotification", " :"+notificationData.size());
Log.d("sizeNotificationDummy", " :"+notificationData.size());
Log.d("isiHideAdapter", Arrays.toString(indexForHide.toArray()));
Log.d("isiHideAdapterSize", indexForHide.size()+"");
}
#Override
protected int getItemResourceLayout(int viewType) {
return R.layout.item_notification_list;
}
int position;
#Override
public int getItemViewType(int position) {
this.position = position;
return position;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
setChildNotif();
return new CustomViewHolder(getView(parent, viewType), onItemClickListener);
}
public class CustomViewHolder extends BaseViewHolder<NotificationData> {
private TextView tvNotifTitle, tvNotifBody, tvNotifStatus, tvNotifTime, tvSignUnread, tvHeaderTitle;
private CardView formContent;
private LinearLayout linearLayout_childItems;
private ImageView expandList;
public CustomViewHolder(View itemView, OnItemClickListener onItemClickListener) {
super(itemView, onItemClickListener);
tvNotifTitle = itemView.findViewById(R.id.tvNotifTitle);
tvNotifBody = itemView.findViewById(R.id.tvNotifBody);
// tvNotifStatus = itemView.findViewById(R.id.tvNotifStatus);
tvNotifTime = itemView.findViewById(R.id.tvNotificationTime);
formContent = itemView.findViewById(R.id.formContent);
tvSignUnread = itemView.findViewById(R.id.tvSignUnread);
tvHeaderTitle = itemView.findViewById(R.id.tvHeaderNotifList);
linearLayout_childItems = itemView.findViewById(R.id.ll_child_items);
expandList = itemView.findViewById(R.id.arrow_expand_notif_list);
//SET CHILD
int intMaxNoOfChild = 0;
for (int index = 0; index < notificationData.size(); index++) {
int intMaxSizeTemp = notificationData.get(index).getChildNotification().size();
if (intMaxSizeTemp > intMaxNoOfChild) intMaxNoOfChild = intMaxSizeTemp;
}
linearLayout_childItems.removeAllViews();
for (int indexView = 0; indexView < intMaxNoOfChild; indexView++) {
TextView textView = new TextView(context);
textView.setId(indexView);
textView.setPadding(20, 20, 0, 20);
textView.setGravity(Gravity.LEFT);
textView.setTextSize(14);
textView.setTextColor(ContextCompat.getColor(context, R.color.colorText));
textView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_sub_notif_text));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 16;
textView.setOnClickListener(this);
linearLayout_childItems.addView(textView, layoutParams);
}
}
#Override
public void bind(NotificationData item) {
String title = splitString(item.getTitle());
tvNotifTitle.setText(title);
tvNotifBody.setText(item.getContent());
String txtTime = item.getCreatedAtDisplay().replaceAll("WIB", "");
tvNotifTime.setText(txtTime);
if (position == 0) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).topMargin = dpToPx(12);
}
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(12);
if (position == getItemCount() - 1) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(80);
}
if(item.getIsRead()==1){
formContent.setCardBackgroundColor(context.getResources().getColor(R.color.gray1));
formContent.setCardElevation(5);
formContent.setRadius(15);
tvSignUnread.setVisibility(View.GONE);
}else if(item.getIsRead()==0){
}
//setHeader
Calendar calendar;
SimpleDateFormat dateFormat;
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
String date, yesterdayDate, dateDisplayData, dateData;
date = dateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
yesterdayDate = dateFormat.format(calendar.getTime());
String[] arrDateDisplayData = item.getCreatedAtDisplay().split(",", 5);
dateDisplayData = arrDateDisplayData[0];
String[] arrDateData = item.getCreatedAt().split(" ", 5);
dateData = arrDateData[0];
Log.d("datenow", date);
Log.d("dateyesterday", yesterdayDate);
Log.d("dateDisplayData", dateDisplayData);
Log.d("dateData", dateData);
if(dateData.equalsIgnoreCase(date)){
tvHeaderTitle.setText("Hari ini");
}else if(dateData.equalsIgnoreCase(yesterdayDate)){
tvHeaderTitle.setText("Kemarin");
}else{
tvHeaderTitle.setText(dateDisplayData);
// tvHeaderTitle.setVisibility(View.GONE);
}
if (getAdapterPosition() > 0) {
String[] timePrev = notificationData.get(getAdapterPosition() - 1).getCreatedAt().split(" ");
if (dateData.equalsIgnoreCase(timePrev[0])) {
tvHeaderTitle.setVisibility(View.GONE);
}
}
if(indexForHide.contains(getAdapterPosition())){
formContent.setVisibility(View.GONE);
}
//SET CHILD
NotificationData dummyParentDataItem = notificationData.get(position);
int noOfChildTextViews = linearLayout_childItems.getChildCount();
for (int index = 0; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
currentTextView.setVisibility(View.VISIBLE);
}
int noOfChild = 0;
if(dummyParentDataItem.getChildNotification()==null){
noOfChild = 0;
}else{
noOfChild = dummyParentDataItem.getChildNotification().size();
}
if (noOfChild < noOfChildTextViews) {
for (int index = noOfChild; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
// currentTextView.setVisibility(View.GONE);
}
}
for (int textViewIndex = 0; textViewIndex < noOfChild; textViewIndex++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(textViewIndex);
currentTextView.setText(dummyParentDataItem.getChildNotification().get(textViewIndex).getTitle());
/*currentTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "" + ((TextView) view).getText().toString(), Toast.LENGTH_SHORT).show();
}
});*/
}
if (noOfChild > 0) {
expandList.setVisibility(View.VISIBLE);
expandList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (linearLayout_childItems.getVisibility() == View.VISIBLE) {
linearLayout_childItems.setVisibility(View.GONE);
// Toast.makeText(context, "expand", Toast.LENGTH_SHORT).show();
expandList.setImageResource(R.drawable.ic_arrow_up_blue);
}
else {
linearLayout_childItems.setVisibility(View.VISIBLE);
expandList.setImageResource(R.drawable.ic_arrow_down_blue);
}
}
});
}else {
linearLayout_childItems.setVisibility(View.GONE);
}
}
public int dpToPx(int dp) {
Resources r = context.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp, r.getDisplayMetrics()
);
return px;
}
public String splitString(String tempString){
StringBuilder finalString = new StringBuilder(tempString);
int i = 0;
while ((i = finalString.indexOf(" ", i + 20)) != -1) {
finalString.replace(i, i + 1, "\n");
}
return finalString.toString();
}
}
}
please help me to render my layout whenever i want to make a child list under my parent list so i can simplify my code above and not making the child layout programatically
I'm creating an app where I have radio group with three radio buttons. What I want is when I check the radio button I need to get the id value of that radio button and save it in array or database and then count the id value.
For example i have this radiogroup in 19 fragment. which is each radiobutton has id value. if the button selected, it will get the id and store it so i can count the selected id value.
this is the display of my stepperstone
My StepFragment
Bundle bundle = this.getArguments();
Log.d("##", "onCreateView: " + bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)) ;
View view = inflater.inflate(R.layout.fragment_step_fragment_example, container, false);
mRadioGroup = view.findViewById(R.id.radioGroupWrapper);
mRadioGroup.getCheckedRadioButtonId();
DatabaseHelper mDBHelper = new DatabaseHelper(getContext());
Log.d("#######", String.valueOf(bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)));
final List<Klasifikasi> lk = mDBHelper.getListKlasifikasiByGroup(String.valueOf(Integer.valueOf(bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)) + 1));
final RadioButton[] rb = new RadioButton[lk.size()];
Log.d("##sz", "onCreateView: " + lk.size()) ;
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.BLACK,
Color.BLACK,
Color.BLACK
};
mRadioButton1 = view.findViewById(R.id.checkbox1);
mRadioButton2 = view.findViewById(R.id.checkbox2);
mRadioButton3 = view.findViewById(R.id.checkbox3);
if(lk.size() > 0) {
Klasifikasi kl0 = lk.get(0);
Klasifikasi kl1 = lk.get(1);
Klasifikasi kl2 = lk.get(2);
mRadioButton1.setText(kl0.getKlasifikasi());
mRadioButton2.setText(kl1.getKlasifikasi());
mRadioButton3.setText(kl2.getKlasifikasi());
}
My StepperAdapter
public static final String CURRENT_STEP_POSITION_KEY = "CURRENT_STEP_POSITION_KEY";
public MyStepperAdapter(FragmentManager fm, Context context) {
super(fm, context);
}
#Override
public Step createStep(int position) {
final StepFragmentExample step = new StepFragmentExample();
Bundle b = new Bundle();
b.putInt(CURRENT_STEP_POSITION_KEY, position);
step.setArguments(b);
return step;
}
#Override
public int getCount() {
return 19;
}
#NonNull
#Override
public StepViewModel getViewModel(#IntRange(from = 0) int position) {
//Override this method to set Step title for the Tabs, not necessary for other stepper types
return new StepViewModel.Builder(context)
.setTitle("Fragment " + getCount()) //can be a CharSequence instead
.create();
}
ListKlasifikasiAdapter
public ListKlasifikasiAdapter.KlasifikasiViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.item_listklasifikasi, viewGroup, false);
KlasifikasiViewHolder klasifikasiViewHolder = new KlasifikasiViewHolder(view);
klasifikasiViewHolder.setIsRecyclable(false);
return klasifikasiViewHolder;
}
#Override
public void onBindViewHolder(#NonNull KlasifikasiViewHolder klasifikasiViewHolder, int i) {
final List<Klasifikasi> lk = mDBHelper.getListKlasifikasiByGroup(String.valueOf(mKlasifikasiList.get(i).getGroup_index()));
final RadioButton[] rb = new RadioButton[lk.size()];
for (int j = 0; j < lk.size(); j++) {
Klasifikasi kl = lk.get(j);
rb[j] = new RadioButton(mContext);
rb[j].setId(j);
rb[j].setText(kl.getKlasifikasi());
klasifikasiViewHolder.radioGroup.addView(rb[j]);
}
}
class KlasifikasiViewHolder extends RecyclerView.ViewHolder {
private RadioGroup radioGroup;
public KlasifikasiViewHolder(#NonNull View itemView) {
super(itemView);
radioGroup = itemView.findViewById(R.id.radioGroupWrapper);
}
}
MyDatabaseHelper
public List<Klasifikasi> getListKlasifikasiByGroup(String index){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi k WHERE k.group_index = ? ORDER BY k.kategori_id ASC", new String[] {index});
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3), cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
ga ada yg jawab T^T cries in the corner
Can not trigger on Click listener
I tried
setClickable(true);
but still not working
minimum sdk is 15
the code doesn't have xml file, i need to fix it programmatically
the complete code:
public class MainActivity extends AppCompatActivity {
private static char CHAR = 'a';
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
int rowNo = ROWS;
int colNo = (screenWidth().widthPixels * ROWS /screenWidth().heightPixels) ;
for (int i = 0; i < 5; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
for (int j = 0; j < 5; j++) {
String txt = String.valueOf(CHAR);
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + txt);
}
});
row.addView(cell);
CHAR += 1;
}
layout.addView(row);
}
setContentView(layout);
}
private class Cell extends LinearLayout{
public Cell(Context context, final String value, int width, int height) {
super(context);
LinearLayout.LayoutParams cellParams = new LinearLayout.LayoutParams(width, height);
setLayoutParams(cellParams);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(getGradientDrawable());
}else{
setBackgroundDrawable(getGradientDrawable());
}
}
private GradientDrawable getGradientDrawable() {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setColor(Color.TRANSPARENT);
shape.setStroke(2, Color.BLACK);
return shape;
}
}
}
so, why and how to fix it.
at clicking the associated text will be printed
Try onClickListener inside your loop
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + value);
}
});
I am having some problems when trying to trigger events on table layout in Android. These are the codes I used to populate the table layout dynamically:
private void BuildTable() {
try {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Category.this);
mDbHelper.open();
CategoryController cc = new CategoryController(mDbHelper.open());
Cursor mCur = mDb.rawQuery(cc.getAllCat(), null);
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
// Setting table header
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
do {
int cols = mCur.getColumnCount();
row = new TableRow(this);
for (int j = 1; j < cols; j++) {
// Dynamically load data fetch from database
// into table layout
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setPadding(5, 5, 10, 5);
tv.setGravity(Gravity.LEFT);
tv.setText(mCur.getString(j));
row.addView(tv);
row.setId(j);
}
row.setClickable(true);
row.setOnClickListener(tablerowOnClickListener);
table_layout.addView(row);
} while (mCur.moveToNext());
}
}
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
And here is my table row onClickListener:
private OnClickListener tablerowOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Highlight selected row
v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
final int k = v.getId();
Toast.makeText(Category.this, Integer.toString(k),
Toast.LENGTH_SHORT).show();
}
};
My problem is when I highlighted certain row and I select another row again, the previous highlighted row remains the same highlighted background color. I wonder how to solve it?
Thanks in advance.
Provided table_layout is in the same scope as tablerowOnClickListener, change the Listener as follows:
private OnClickListener tablerowOnClickListener = new OnClickListener()
{
public void onClick(View v)
{
//Highlight selected row
for (int i = 0; i < table_layout.getChildCount(); i++)
{
View row = table_layout.getChildAt(i);
if (row == v)
{
row.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
else
{
//Change this to your normal background color.
row.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
//...
}
};
While I am adding textviews to relative layout, at the end of first line, the textview is going wrong.
as shown in below:
.
here is my code to diplay textviews.
public void showkeyword()
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout fl = (RelativeLayout)findViewById(R.id.key_layout);
fl.removeAllViews();
RelativeLayout.LayoutParams params ;
//TextView key = (TextView) inflater.inflate(R.layout.tag_keyword,null);
i = 0;
for(String s : alist)
{
TextView textview = (TextView) inflater.inflate(R.layout.tag_keyword,null);
textview.setText(s);
textview.setId(2000 + i);
if (i == 0) {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textview.setLayoutParams(rlp2);
fl.addView(textview);
} else {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// rlp2.addRule(RelativeLayout.ALIGN_BASELINE);
rlp2.setMargins(10,0, 10,0);
rlp2.addRule(RelativeLayout.RIGHT_OF, textview.getId() - 1);
textview.setLayoutParams(rlp2);
fl.addView(textview);
}
i++;
}
}
I wish to have something like this, sort of a tab implementation:
Hope the following code will help you out:
Functioning:
contactWrapper is a linear layout, we go on adding the textviews into these linear layouts one by one and before adding find whether the contactWrapper has space enough to put in the next TextView, if not a new linear layout is created and the textViews are added into it.
Take time analyzing the following code.
public void drawLayout() {
int counter = 0;
contactWrapperWidth = getResources().getDisplayMetrics().widthPixels;
contactWrapper.setOrientation(LinearLayout.VERTICAL);
// contact wrapper is a linear Layout
// use LinearLayout contactWrapper = (LinearLayout) mView
// .findViewById(R.id.yourLinearLayout);
currCounter = 0;
currWidth = 0;
isNewLine = false;
row[currCounter] = new LinearLayout(getActivity());
#SuppressWarnings("rawtypes")
Iterator it = button.iterator();
for (int i = 0; i < button.size(); i++) {
it.next();
row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
currWidth += Integer
.parseInt(button.get(i).get("width").toString());
Log.i("Item width ", "i == "
+ button.get(i).get("width").toString());
// contactWrapper.getw
if (isNewLine) {
if (currWidth < contactWrapperWidth) {
row[currCounter]
.addView((View) button.get(i).get("button"));
if (!it.hasNext()) {
contactWrapper.addView(row[currCounter]);
} else {
if (contactWrapperWidth < (currWidth + Integer
.parseInt(button.get(i + 1).get("width")
.toString()))) {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
} else {
isNewLine = false;
}
}
} else {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
}
} else {
if (currWidth < contactWrapperWidth) {
if (!it.hasNext()) {
View view = (View) button.get(i).get("button");
row[currCounter].addView((View) button.get(i).get(
"button"));
contactWrapper.addView(row[currCounter]);
} else {
View view = (View) button.get(i).get("button");
row[currCounter].addView((View) button.get(i).get(
"button"));
if (contactWrapperWidth < (currWidth + Integer
.parseInt(button.get(i + 1).get("width")
.toString()))) {
isNewLine = true;
Logger.show(Log.INFO, "it.hasNext()",
"it.hasNext() contactWrapper");
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
} else {
isNewLine = false;
}
}
} else {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
}
}
counter++;
}
}
Finally I am able to remove that bug using idea by #kailas
Here I am posting my method:
public void showkeyword() {
int counter = 0;
int screenWidth = getResources().getDisplayMetrics().widthPixels;
final RelativeLayout contactWrapper = (RelativeLayout)findViewById(R.id.key_layout);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams buttonparams = new RelativeLayout.LayoutParams(
150,
80);
int i = 0;
contactWrapper.removeAllViews();
// contact wrapper is a linear Layout
// use LinearLayout contactWrapper = (LinearLayout) mView
// .findViewById(R.id.yourLinearLayout);
int currCounter = 0;
int currWidth = 0;
boolean isNewLine = false;
boolean firstLine = true;
for(final String s : alist)
{
TextView textview = new TextView(this);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp1.setMargins(7, 5, 7, 0);
textview.setText(s);
textview.setId(2000 + i);
textview.setBackgroundColor(Color.DKGRAY);
textview.setTextColor(Color.CYAN);
textview.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contactWrapper.removeView(v);
alist.remove(s);
}
});
int width = s.length()*15;
if((currWidth+width+150)<=screenWidth)
{
currWidth += width+10;
isNewLine = false;
currCounter++;
}
else{
currWidth = width+14;
firstLine = false ;
isNewLine = true;
currCounter=1;
}
if(i==0)
{ rlp1.addRule(RelativeLayout.ALIGN_START);
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else if(isNewLine){
rlp1.addRule(RelativeLayout.ALIGN_LEFT);
rlp1.addRule(RelativeLayout.BELOW,2000-1+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else if(firstLine)
{
rlp1.addRule(RelativeLayout.RIGHT_OF,2000-1+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else{
rlp1.addRule(RelativeLayout.RIGHT_OF,2000-1+i );
rlp1.addRule(RelativeLayout.BELOW,2000-currCounter+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
i++;
}
buttonparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
buttonparams.addRule(RelativeLayout.ALIGN_BASELINE,2000-1+i);
Button clearbtn = new Button(this);
clearbtn.setText("clear");
// clearbtn.setBackgroundColor(Color.RED);
// clearbtn.setTextColor(Color.CYAN);
clearbtn.setLayoutParams(buttonparams);
clearbtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contactWrapper.removeAllViews();
alist.clear();
}
});
contactWrapper.addView(clearbtn) ;
}
Try to remove
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
because the behavior you want is the default behavior.
Put Orientation horinzontal in the relative layout.
Try using a LinearLayout and a fixed height (using the dip unit) instead of WRAP_CONTENT
Try to put all the text you want in one String and then put all this text in only one TextView.
The best way is using StringBuilder to concat the text:
StringBuilder sb = new StringBuilder();
sb.append("str1");
sb.append("str2");
and then put the string in the textview
textview.setText(sb.toString());