I am writing an app where I need to create a custom ImageView (in order to override its onDraw). After failing to do that for a couple of weeks I created a minimal, reproducible example which captures the problem. Here is the code:
package com.nzeldes.mytestapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
CustomImageView myImageView;
Bitmap myBitmap;
class CustomImageView extends androidx.appcompat.widget.AppCompatImageView {
public CustomImageView(#NonNull Context context) {
super(context);
}
public CustomImageView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int displaywidth = Resources.getSystem().getDisplayMetrics().widthPixels;
myBitmap = Bitmap.createBitmap(displaywidth, displaywidth, Bitmap.Config.ARGB_8888);
myBitmap.eraseColor(Color.BLACK);
myImageView = findViewById(R.id.imageView); // Get a reference to the ImageView
myImageView.setImageBitmap(myBitmap); // Associate the bitmap to the ImageView
}
}
and the XML layout:
*<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="403dp"
android:layout_height="366dp"
android:layout_marginTop="72dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
</androidx.constraintlayout.widget.ConstraintLayout>*
However, in the source window I get a “Unexpected implicit cast to CustomImageView: layout tag was ImageView” warning on myImageView = findViewById(R.id.imageView);
And if I try to run the app it crashes with this error from Logcat:
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageView cannot be cast to com.nzeldes.mytestapp.MainActivity$CustomImageView
I admit to being new to Android (putting the lockdown times to some use learning something new!)... any help will be most appreciated.
For inner classes the syntax becomes:
<view class="{package}.{ParentClass}${innerClass}"
Please change your layout like the code below
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<view class="com.nzeldes.mytestapp.MainActivity$CustomImageView"
android:id="#+id/imageView"
android:layout_width="403dp"
android:layout_height="366dp"
android:layout_marginTop="72dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
</androidx.constraintlayout.widget.ConstraintLayout>
Related
Previously I had crash issues due to the wrong reference to the resource files. Fixed that issue and updated this thread with the logical error that I am getting.
I am new to android and currently learning custom classes and adapter. While working I am facing a problem which is the listview shows the first arraylist item only.
I have attached the codes of the required files as well.
Working Activity
package np.com.shresthakiran.tourswoniga;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class KhowpaActivity extends AppCompatActivity {
ListView lvHeritageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_heritage);
lvHeritageList = findViewById(R.id.lvHeritage);
ArrayList<Heritages> heritageAryList = new ArrayList<>();
heritageAryList.add(new Heritages(R.drawable.ic_launcher_background,"Ngatapol", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Dattatreya", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Lu dhwakha", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "55 jhyale Durbar", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Taleju Bhawani", "Lyaaku"));
HeritageAdapter heritageAdapter = new HeritageAdapter(KhowpaActivity.this, R.layout.heritages_row, heritageAryList);
lvHeritageList.setAdapter(heritageAdapter);
}
}
Custom Adapter
package np.com.shresthakiran.tourswoniga;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HeritageAdapter extends ArrayAdapter<Heritages> {
private Context mContext;
private int mResource;
public HeritageAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Heritages> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater =LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
ImageView ivHeritageImage = convertView.findViewById(R.id.ivHeritage);
TextView tvHeritageName = convertView.findViewById(R.id.tvHeritageName);
TextView tvHeritageAddress = convertView.findViewById(R.id.tvHeritageAddress);
ivHeritageImage.setImageResource(getItem(position).getmImageResourceId());
tvHeritageName.setText(getItem(position).getmHeritageName());
tvHeritageAddress.setText(getItem(position).getmHeritageAddress());
return convertView;
}
}
Object Class
package np.com.shresthakiran.tourswoniga;
public class Heritages {
private int mImageResourceId;
private String mHeritageName;
private String mHeritageAddress;
public Heritages(int heritageImageResourceId, String heritageName, String heritageAddress) {
this.mImageResourceId = heritageImageResourceId;
this.mHeritageName = heritageName;
this.mHeritageAddress = heritageAddress;
}
public int getmImageResourceId() {
return mImageResourceId;
}
public String getmHeritageName() {
return mHeritageName;
}
public String getmHeritageAddress() {
return mHeritageAddress;
}
}
ListView XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="100dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvHeritage">
</ListView>
</RelativeLayout>
List Row XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_margin="10dp">
<ImageView
android:id="#+id/ivHeritage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="33.33"
android:padding="2dp"
android:text="Ngatapol"
android:layout_marginTop="7dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:id="#+id/llHeritageInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="66.66"
android:padding="8dp" >
<TextView
android:id="#+id/tvHeritageName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"
android:text="Ngatapol"
android:textAppearance="?android:textAppearanceMedium"
android:padding="2dp"/>
<TextView
android:id="#+id/tvHeritageAddress"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:text="Taumadi"
android:padding="2dp"/>
</LinearLayout>
</LinearLayout>
listview shows the first item only is because you have set height in heritages_row layout to match_parent which will cover the whole screen height and for the next item, you've to scroll down even if the content of the first item is not covering the whole height.
To make each row to only cover the content its displaying, use wrap_content instead of match_parent.
I am new to android and I am a bit stuck. I am trying to create a simple drawing app which shows an example on the top of the page and a square space for it in below it. Aim is to display a letter and a kid needs to practice in replicating it.
I have troubles including the drawing class in the layout which needs to restrict its boundaries.
this is the main layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/exampleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
enter code here` android:id="#+id/drawingBoard"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/exampleText">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
this is the PaintView class
import android.app.ActionBar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
public class PaintView extends View {
public ViewGroup.LayoutParams param;
private Path path = new Path();
private Paint brush = new Paint();
public PaintView(MainActivity context) {
super(context);
brush.setAntiAlias(true);
brush.setColor(Color.RED);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(8f);
param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX,pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX,pointY);
break;
default:
return false;
}
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path,brush);
}
this is how it is called in the Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PaintView paintView = new PaintView(this);
setContentView(paintView);
}
I need to fit the drawing board into the "drawingBoard".
It is not necessary the right approach, but this is as far as I got.
Thanks in advance
Attach the customview to a fragment.
This is a completely different approach so you will have to make a lot of changes to your code.
The other approach would be adding the view programmatically to the ConstraintLayout.
In MainActivity,
protected void onCreate(Bundle savedInstanceStatee) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//remove those lines.
/*
PaintView paintView = new PaintView(this);
setContentView(paintView);*/
ConstraintLayout parentLayout = (ConstraintLayout)findViewById(R.id.drawingBoard);
ConstraintSet set = new ConstraintSet();
PaintView paintView = new PaintView(this);
// set view id, else getId() returns -1
paintView.setId(View.generateViewId());
layout.addView(paintView, 0);
set.clone(parentLayout);
// connect start and end point of views, in this
case top of child to top of parent.
set.connect(paintView.getId(),
ConstraintSet.TOP,parentLayout.getId(),
ConstraintSet.TOP, 60);
// ... similarly add other constraints
set.applyTo(parentLayout);
}
In the activity you are overwriting the content view with just the paint view:
setContentView(paintView);
Remove that line.
Add the PaintView in XML instead:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/exampleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- TODO: Replace with your package name -->
<com.example.PaintView
android:id="#+id/drawingBoard"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/exampleText" />
</androidx.constraintlayout.widget.ConstraintLayout>
With this approach you have to inflate the custom view in its constructors:
public class PaintView extends ConstraintLayout {
public PaintView(#NonNull Context context) {
super(context);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public void init() {
inflate(getContext(), R.layout.layout_product_item, this);
}
}
To interact with the PaintView from the activity code you can do:
PaintView paintView = (PaintView) findViewById(R.id.drawingBoard);
So, I have followed this tutorial (https://www.youtube.com/watch?v=cS5l_hPwC10) on how to do a card stack and it works fine even with 2 cardstacks at the same time. now I want to add a button so i can reset both stacks and/or a button to get to the previous card
Here is all the code I have related to the card stack. Tell me if you need more since this is the first time I am trying to programm something
hauptanwendung_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHauptanwendung">
<com.wenchao.cardstack.CardStack
android:id="#+id/card_stack"
android:layout_width="280dp"
android:layout_height="170dp"
android:clipChildren="false"
android:clipToPadding="false" />
<com.wenchao.cardstack.CardStack
android:id="#+id/card_stack2"
android:layout_width="280dp"
android:layout_height="170dp"
android:clipChildren="false"
android:clipToPadding="false" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/stern"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
app:srcCompat="#drawable/ic_stern02" />
<Space
android:layout_width="50sp"
android:layout_height="match_parent"
android:layout_marginRight="15sp"
android:layout_weight="1" />
<ImageButton
android:id="#+id/stift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
app:srcCompat="#drawable/ic_bearbeiten01" />
</LinearLayout>
</LinearLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center" />
</LinearLayout>
card_layout2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image_content2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center" />
</LinearLayout>
FragmentHauptanwendung.java
package com.example.ideenfinder3;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.wenchao.cardstack.CardStack;
import java.util.Objects;
public class FragmentHauptanwendung extends Fragment implements CardStack.CardEventListener {
View view;
private CardsDataAdapter card_adapter;
private CardsDataAdapter2 card_adapter2;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.hauptanwendung_fragment, container, false);
initImages();
initImages2();
CardStack card_stack = (CardStack) view.findViewById(R.id.card_stack);
card_stack.setContentResource(R.layout.card_layout);
card_stack.setStackMargin(20);
card_stack.setAdapter(card_adapter);
card_stack.setListener(this);
CardStack card_stack2 = (CardStack) view.findViewById(R.id.card_stack2);
card_stack2.setContentResource(R.layout.card_layout2);
card_stack2.setStackMargin(20);
card_stack2.setAdapter(card_adapter2);
card_stack2.setListener(this);
return view;
}
private void initImages2() {
card_adapter2 = new CardsDataAdapter2(Objects.requireNonNull(getActivity()).getApplicationContext(),0);
card_adapter2.add(R.drawable.logo);
card_adapter2.add(R.drawable.schriftzug);
}
private void initImages() {
card_adapter = new CardsDataAdapter(Objects.requireNonNull(getActivity()).getApplicationContext(),0);
card_adapter.add(R.drawable.bild01);
card_adapter.add(R.drawable.bild02);
card_adapter.add(R.drawable.bild03);
card_adapter.add(R.drawable.bild04);
card_adapter.add(R.drawable.bild05);
}
#Override
public boolean swipeEnd(int i, float v) {
return v > 300;
}
#Override
public boolean swipeStart(int i, float v) {
return false;
}
#Override
public boolean swipeContinue(int i, float v, float v1) {
return false;
}
#Override
public void discarded(int i, int i1) {
}
#Override
public void topCardTapped() {
}
}
CardsDataAdapter
package com.example.ideenfinder3;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class CardsDataAdapter extends ArrayAdapter<Integer> {
public CardsDataAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public View getView(int position, final View ImgcontentView, ViewGroup parent){
ImageView ImgV = (ImageView) (ImgcontentView.findViewById(R.id.image_content));
ImgV.setImageResource(getItem(position));
return ImgcontentView;
}
}
CardsDataAdapter2
package com.example.ideenfinder3;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class CardsDataAdapter2 extends ArrayAdapter<Integer> {
public CardsDataAdapter2(#NonNull Context context, int resource) {
super(context, resource);
}
#Override
public View getView(int position, final View ImgcontentView2, ViewGroup parent){
ImageView ImgV2 = (ImageView) (ImgcontentView2.findViewById(R.id.image_content2));
ImgV2.setImageResource(getItem(position));
return ImgcontentView2;
}
}
Just keep handles to CardStack instead:
private CardStack cardStack01;
private CardStack cardStack02;
And let the Fragment implement getters and setters for these.
I am new to android and currently learning right now.
I faced a problem related to android-fragments, I write code and it did nothing! Just show the fragment color.
when I tried to remove the color of the fragment, it worked! I am unable to rectify this problem. Please help!
XML -activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="113dp"
android:layout_height="50dp"
android:text="Switch1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
<fragment
android:id="#+id/fragment"
android:name="com.example.fragments.Color_Purple"
android:layout_width="390dp"
android:layout_height="385dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.68"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
</androidx.constraintlayout.widget.ConstraintLayout>
XML - Fragment code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".Color_Purple">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C403FA" />
</FrameLayout>
JAVA-mainActivity.java
package com.example.fragments;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1;
Fragment f1;
Boolean flag=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
f1=new Color_Purple();
// Toast.makeText(getApplicationContext(),"Button pressed",Toast.LENGTH_SHORT).show();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
if(flag)
{
findViewById(R.id.fragment).setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(),"Button pressed Color GREEN",Toast.LENGTH_SHORT).show();
flag=false;
}
else
{
findViewById(R.id.fragment).setBackgroundColor(Color.RED);
//Toast.makeText(getApplicationContext(),"Button pressed Color RED",Toast.LENGTH_SHORT).show();
flag=true;
}
}
});
}
}
Java - fragment java code
package com.example.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Color_Purple extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_color__purple, container, false);
}
}
Note:
If i remove android:background from xml - fragment, this code works but not with color.
just change :
Boolean flag = true;
to
boolean flag = true;
and remove android:background="#C403FA" from your TextView :
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C403FA" //remove this line
/>
My activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="#+id/mainWindow"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="2"
android:columnCount="2"
android:useDefaultMargins="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="0"
android:background="#drawable/shape"
android:gravity="center"
android:text="Hallo"
/>
</GridLayout>
</android.support.constraint.ConstraintLayout>
How I can add many of this TextFields to the GridLayout in Java.
I tried:
package com.example.sudokusolver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.GridLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayout.LayoutParams lp= new GridLayout.LayoutParams();
lp.width= GridLayout.LayoutParams.MATCH_PARENT;
lp.height= GridLayout.LayoutParams.MATCH_PARENT;
lp.columnSpec= GridLayout.spec(GridLayout.UNDEFINED, 1f);
lp.rowSpec= GridLayout.spec(GridLayout.UNDEFINED, 1f);
TextView textView= new TextView(this);
textView.setBackgroundResource(R.drawable.shape);
textView.setGravity(Gravity.CENTER);
textView.setText("Hallo");
GridLayout grid= findViewById(R.id.gridLayout);
grid.addView(textView);
grid.addView(textView);
}
}
But if i add so more then 1 TextView the error come:
The specified child already has a parent. You must call removeView() on the child's parent first. How I can do this?
You can add a custom view GridChild to your GridLayout which can contain multiple TextViews like this
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="1"
android:columnCount="2"
android:useDefaultMargins="true">
<com.example.customview.GridChild/>
</GridLayout>
and your GridChild class
package com.example.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
public class GridChild extends LinearLayout {
private TextView text1;
private TextView text2;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
inflate(getContext(), R.layout.layout_ll, this);
this.text1 = (TextView)findViewById(R.id.textview1);
this.text2 = (TextView)findViewById(R.id.textview2);
}
}