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());
Related
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);
}
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 have been looking all over SOF and online tutorials, but for some reason I still can't get it to work. I want to implement a drag and drop functionality in my game. Here is the activity:
I want to be able to drag and drop the 4 shapes in the bottom. If the correct shape fits, I want the shape with the "?" to change into the correct shape. Can someone show me how I can do this?
Here is my code:
public class SecondActivity extends AppCompatActivity {
int n;
ImageView shape1, shape2, shape3, shape4, guessShape;
ImageButton exit;
private android.widget.RelativeLayout.LayoutParams layoutParams;
Random rand = new Random();
ImageView[] shapes = new ImageView[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//declare each imageview
shape1 = (ImageView) findViewById(R.id.shape1);
shape2 = (ImageView) findViewById(R.id.shape2);
shape3 = (ImageView) findViewById(R.id.shape3);
shape4 = (ImageView) findViewById(R.id.shape4);
guessShape = (ImageView) findViewById(R.id.guessShape);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
//add each imageView to the shapes[] array
shapes[0] = shape1;
shapes[1] = shape2;
shapes[2] = shape3;
shapes[3] = shape4;
//store all the shapes in an array
int[] images = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4,
R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8, R.drawable.img_9, R.drawable.img_10,
R.drawable.img_11, R.drawable.img_12, R.drawable.img_13, R.drawable.img_14, R.drawable.img_15, R.drawable.img_16,
R.drawable.img_17};
//store all the guessShapes in an array
int[] outlines = new int[]{R.drawable.outline_0, R.drawable.outline_1, R.drawable.outline_2,
R.drawable.outline_3, R.drawable.outline_4, R.drawable.outline_5, R.drawable.outline_6,
R.drawable.outline_7, R.drawable.outline_8, R.drawable.outline_9, R.drawable.outline_10,
R.drawable.outline_11, R.drawable.outline_12, R.drawable.outline_13, R.drawable.outline_14,
R.drawable.outline_15, R.drawable.outline_16, R.drawable.outline_17};
//generate 4 random images from the array's and ensure that they don't match each other
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 18; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
int whichImg = (int) Math.round((Math.random() * 4));
int img1 = list.get(0);
int img2 = list.get(1);
int img3 = list.get(2);
int img4 = list.get(3);
if (whichImg == 1) {
whichImg = img1;
} else if (whichImg == 2) {
whichImg = img2;
} else if (whichImg == 3) {
whichImg = img3;
} else {
whichImg = img4;
}
int outlineID = outlines[whichImg];
//set the shape in each imageview
guessShape.setBackgroundResource(outlineID);
shape1.setBackgroundResource(images[img1]);
shape2.setBackgroundResource(images[img2]);
shape3.setBackgroundResource(images[img3]);
shape4.setBackgroundResource(images[img4]);
//ensures that 1/4 shape has the guess shape correspondence
final Object currentBackground = guessShape.getBackground().getConstantState();
//for loop to have the guess shape and 1/4 shapes to match
for (int i = 0; i < 18; i++) {
if (currentBackground.equals(getResourceID("outline_" + i, "drawable", getApplicationContext()))) {
int random = new Random().nextInt(shapes.length);
shapes[random].setBackgroundResource(getResourceID("img_" + i, "drawable", getApplicationContext()));
}
//set tags for each view
guessShape.setTag("gShape");
shape1.setTag("S_1");
shape2.setTag("S_2");
shape3.setTag("S_3");
shape4.setTag("S_4");
}
}
//method to get the ID of an image in drawable folder
protected final static int getResourceID(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
Although you were not clear enough.
Try this, First make a class that implements onTouchListener
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
Then define a drag listener
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(
R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundDrawable(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundDrawable(normalShape);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundDrawable(normalShape);
default:
break;
}
return true;
}
}
Now simply use these lines
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
and
findViewById(R.id.bottomleft).setOnDragListener(new MyDragListener());
Here are some tutorials that might help you
Tutorialpoint
Link 2
java code
package"";
import yuku.ambilwarna.AmbilWarnaDialog;
/**
* Created by pc-4 on 5/31/2016.
*/
public class EditWindow extends ActionBarActivity implements View.OnClickListener {
private static final int SELECT_FILE = 1;
ImageView iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12;
Bitmap myBitmap;
ArrayList<Integer> vericalArrayList = new ArrayList<Integer>();
private LinearLayout hv;
int color = 0xffffff00;
LinearLayout linear_popup;
Context context = this;
String name, meaning;
int j = 0;
LinearLayout[] linearlayout;
LinearLayout ll_main;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_window);
FinBtViewIds();
ll_main.setBackgroundResource(R.drawable.page_back_ground);
linear_popup = (LinearLayout) findViewById(R.id.linear_popup);
Bundle bundle = getIntent().getExtras();
name = bundle.getString("name");
meaning = bundle.getString("meaning");
j = name.length();
linearlayout = new LinearLayout[j];
items = meaning.split("\\s+");
verical_linear();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(EditWindow.this, "FAILES TO SET PIC", Toast.LENGTH_SHORT).show();
}
Drawable drawable = (Drawable) new BitmapDrawable(getResources(), bm);
LinearLayout ll_main = (LinearLayout) findViewById(R.id.linear);
ll_main.setBackground(drawable);
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_background:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.VISIBLE);
break;
case R.id.iv_gallery:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
galleryIntent();
break;
case R.id.iv_text:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
openDialog(true);
break;
case R.id.iv_edit_back:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
onBackPressed();
super.onBackPressed();
break;
case R.id.iv_edit_done:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
ll_main.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(ll_main);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
Intent i=new Intent(EditWindow.this,SaveActivity.class);
startActivity(i);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
break;
case R.id.iv_style:
hv.setVisibility(View.GONE);
if (linear_popup.getVisibility() == View.VISIBLE)
linear_popup.setVisibility(View.GONE);
else {
linear_popup.setVisibility(View.VISIBLE);
}
break;
case R.id.tv_horizontal:
hv.setVisibility(View.GONE);
horizontal_linear();
linear_popup.setVisibility(View.GONE);
break;
case R.id.tv_vertical:
hv.setVisibility(View.GONE);
verical_linear();
linear_popup.setVisibility(View.GONE);
break;
}
}
public void verical_linear() {
ll_main.setOrientation(LinearLayout.VERTICAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
int j = name.length();
final LinearLayout[] linearlayout = new LinearLayout[j];
String[] items = meaning.split("\\s+");
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.HORIZONTAL);
TextView tv = new TextView(this);
int text_id;
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}
tv.setId(text_id);
Toast.makeText(EditWindow.this, String.valueOf(text_id), Toast.LENGTH_SHORT).show();
vericalArrayList.add(text_id);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
t2.setGravity(Gravity.END | Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(2);
t2.setTextSize(20);
t2.setTypeface(face);
t2.setText(items[i]);
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void horizontal_linear() {
ll_main.setOrientation(LinearLayout.HORIZONTAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
int text_id;
tv.setTag(tv.getId());
/*
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}*/
tv.setGravity(Gravity.CENTER);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
/* int text_id2;
Random r1 = new Random();
text_id2 = r1.nextInt();
if (text_id2 < 0) {
text_id2 = text_id2 - (text_id2 * 2);
}*/
t2.setTag(t2.getId());
t2.setGravity(Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(1);
t2.setTypeface(face);
t2.setText(items[i]);
int id=t2.getId();
int id1=tv.getId();
vericalArrayList.add(id);
vericalArrayList.add(id1);
Toast.makeText(EditWindow.this, String.valueOf("1"+id), Toast.LENGTH_SHORT).show();
Toast.makeText(EditWindow.this, String.valueOf("2"+id1), Toast.LENGTH_SHORT).show();
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void FinBtViewIds() {
final ImageView tv_horizontal;
final ImageView tv_vertical;
final ImageView iv_edit_back;
final ImageView iv_done;
final ImageView iv_gallery;
final ImageView iv_background;
final ImageView iv_style;
final ImageView iv_text;
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
iv4=(ImageView)findViewById(R.id.iv4);
iv5=(ImageView)findViewById(R.id.iv5);
iv6=(ImageView)findViewById(R.id.iv6);
iv7=(ImageView)findViewById(R.id.iv7);
iv8=(ImageView)findViewById(R.id.iv8);
iv9=(ImageView)findViewById(R.id.iv9);
iv10=(ImageView)findViewById(R.id.iv10);
iv11=(ImageView)findViewById(R.id.iv11);
iv12=(ImageView)findViewById(R.id.iv12);
ll_main = (LinearLayout) findViewById(R.id.linear);
hv = (LinearLayout) findViewById(R.id.hv);
iv_edit_back = (ImageView) findViewById(R.id.iv_edit_back);
tv_horizontal = (ImageView) findViewById(R.id.tv_horizontal);
tv_vertical = (ImageView) findViewById(R.id.tv_vertical);
iv_done = (ImageView) findViewById(R.id.iv_edit_done);
iv_gallery = (ImageView) findViewById(R.id.iv_gallery);
iv_background = (ImageView) findViewById(R.id.iv_background);
iv_style = (ImageView) findViewById(R.id.iv_style);
iv_text = (ImageView) findViewById(R.id.iv_text);
iv_edit_back.setOnClickListener(this);
iv_done.setOnClickListener(this);
iv_gallery.setOnClickListener(this);
iv_background.setOnClickListener(this);
iv_style.setOnClickListener(this);
iv_text.setOnClickListener(this);
tv_horizontal.setOnClickListener(this);
tv_vertical.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
}
}
void openDialog(boolean supportsAlpha) {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(EditWindow.this, color, supportsAlpha, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
//Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
EditWindow.this.color = color;
displayColor();
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
// Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
void displayColor() {
for (int i = 0; i < vericalArrayList.size(); i++) {
String id = vericalArrayList.get(i).toString();
TextView text = (TextView) findViewById(vericalArrayList.get(i));
text.setTextColor(color);
Toast.makeText(EditWindow.this, id + "/n" + i, Toast.LENGTH_SHORT).show();
}
}
public void Onclick(View v)
{
switch (v.getId())
{
case R.id.iv1:
ll_main.setBackgroundResource(R.drawable.n1);
break;
case R.id.iv2:
ll_main.setBackgroundResource(R.drawable.n2);
break;
case R.id.iv3:
ll_main.setBackgroundResource(R.drawable.n3);
break;
case R.id.iv4:
ll_main.setBackgroundResource(R.drawable.n4);
break;
case R.id.iv5:
ll_main.setBackgroundResource(R.drawable.n5);
break;
case R.id.iv6:
ll_main.setBackgroundResource(R.drawable.n6);
break;
case R.id.iv7:
ll_main.setBackgroundResource(R.drawable.n7);
break;
case R.id.iv8:
ll_main.setBackgroundResource(R.drawable.n8);
break;
case R.id.iv9:
ll_main.setBackgroundResource(R.drawable.n9);
break;
case R.id.iv10:
ll_main.setBackgroundResource(R.drawable.n10);
break;
case R.id.iv11:
ll_main.setBackgroundResource(R.drawable.n11);
break;
case R.id.iv12:
ll_main.setBackgroundResource(R.drawable.n12);
break;
}
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
}
xml
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#color/white"
android:orientation="horizontal"
android:padding="#dimen/value_10"
android:visibility="visible">
</LinearLayout>
i didn't post imports
WHOLE XML DOENOT MATTER HERE SO I JUST here playing with single linearlayout so have added only that
have added full codes
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTextColor(int)' on a null object reference
As you are storing all TextView ids in array list and the only thing you need to do is cast that view to TextView and set text color.
TextView text = (TextView) findViewById(integerArrayList.get(i));
text.setTextColor(Color.RED);
I am a complete beginner in android. I am stuck at a point in making an application. I have images stored in hashmap and whatever line I give it as an input is broken into separate words on basis of space and its corresponding images are fetched. But I dont want these images to show up at once but these should be shown one after the other and there should be a pause of almost one second between each image to show up. But seems like I am stuck because of my inexperience. In code where and how should I place a pause? Because when I use Thread.sleep anywhere in code, it pause only in beginning everytime.
textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Speech.setText("You said " + matches_text.get(position));
selectedFromList = (matches_text.get(position));
String[] separated = selectedFromList.split(" ");
// ImageView iv;
final int[] imageViews = { R.id.imageView1,
R.id.imageView2, R.id.imageView3, R.id.imageView4,
R.id.imageView5, R.id.imageView6, R.id.imageView7,
R.id.imageView8, R.id.imageView9, R.id.imageView10,
R.id.imageView11, R.id.imageView12,
R.id.imageView13, R.id.imageView14,
R.id.imageView15, R.id.imageView16,
};
final_length = separated.length;
int b = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple",R.drawable.apple);
maps pol=new maps();
pol.map_A();
pol.map_B();
pol.map_C();
pol.map_D();
pol.map_E();
for (int i = 0; i < separated.length; i++) {
iv = (ImageView) findViewById(imageViews[i]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_a.get(separated[i].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_b.get(separated[i].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_c.get(separated[i].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_d.get(separated[i].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_e.get(separated[i].toLowerCase()));
}
}}
Change your for loop as following:
Handler handler1 = new Handler();
for (int i = 0; i < separated.length; i++) {
final int iDupe = i;
handler1.postDelayed(new Runnable() {
public void run() {
iv = (ImageView) findViewById(imageViews[iDupe]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_a.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_b.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_c.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_d.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_e.get(separated[iDupe].toLowerCase()));
}
}
}, i * 1000);
}