This is my first attempt with TypedArrays and I believe I've written my code correctly, but for some reason I am only able to see the first image in my array. I have a loop that should be displaying the images repeatedly.
My activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="wrap_content" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".HomeScreen"
android:background="#android:drawable/screen_background_dark_transparent"
android:clickable="true"
android:id="#+id/homescreen_view">
<Button
android:layout_width="100.0dp"
android:layout_height="25.0dp"
android:text="Help"
android:id="#+id/instructionsButton"
android:layout_alignParentTop="false"
android:layout_alignParentStart="true"
android:textColor="#05ffda"
android:background="#android:color/holo_purple"
android:longClickable="true" />
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="centerCrop"
android:id="#+id/soundEnable_button"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:longClickable="true"
android:nestedScrollingEnabled="true"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="100dp"
android:layout_height="25dp"
android:text="Highscores"
android:id="#+id/highscores_button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_purple"
android:textColor="#05ffda" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="100dp"
android:layout_height="30dp"
android:text="Play Game"
android:id="#+id/startGame_button"
android:background="#android:color/holo_purple"
android:textColor="#05ffda"
android:layout_marginTop="175dp"
android:singleLine="true"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="musicIcon">
<item>#drawable/musicoff</item>
<item>#drawable/musicon1</item>
<item>#drawable/musicon2</item>
<item>#drawable/musicon3</item>
<item>#drawable/musicon4</item>
<item>#drawable/musicon5</item>
</array>
</resources>
and my activity.java
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class HomeScreen extends AppCompatActivity {
ImageButton musicEnable_ImageButton;
Handler musicIcon_animate = new Handler();
int ArrayPos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final TypedArray musicIcons = getResources().obtainTypedArray(R.array.musicIcon);
for(ArrayPos =0;ArrayPos<5;ArrayPos++) {
musicIcons.getResourceId(ArrayPos, -1);
}
ArrayPos = 0;
musicEnable_ImageButton = (ImageButton) findViewById(R.id.soundEnable_button);
musicEnable_ImageButton.setImageResource(musicIcons.getResourceId(ArrayPos,-1));
musicIcons.recycle();
musicEnable_ImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ArrayPos = 1;
Runnable runnable = new Runnable() {
#Override
public void run() {
musicEnable_ImageButton.setImageResource(musicIcons.getResourceId(ArrayPos,-1));
musicIcons.recycle();
if(ArrayPos < 5) {
ArrayPos++;
}
else{
ArrayPos = 1;
}
Log.d("test", "timer fired");
musicIcon_animate.postDelayed(this, 1);
}
};
musicIcon_animate.postDelayed(runnable, 1);
}
});
}
You can only see the first image because you are recycling your musicIcons TypedArray after you set the first image. TypedArray.recycle() removes all of the references to the resources in the array, making it an empty array. You want to do this, but only after you've gotten what you need from the array.
In your case, since you are using the resources over a period of time, I would suggest doing something like this:
List<Integer> musicIcons = new ArrayList<>();
final TypedArray typedArray = getResources().obtainTypedArray(R.array.musicIcon);
for(int i = 0; i < typedArray.length(); i++) {
musicIcons.add(typedArray.getResourceId(i, -1);
}
typedArray.recycle();
Then set the ImageView resource like this:
musicEnable_ImageButton.setBackgroundResource(musicIcons.get(ArrayPos));
But, I also noticed that it looks like you are just trying to animate the icon, in which case, you should look into using an AnimationDrawable. In this way you can just create a drawable XML file:
<animation-list android:id="#+id/selected" android:oneshot="true">
<item android:drawable="#drawable/musicoff" android:duration="50" />
<item android:drawable="#drawable/musicon1" android:duration="50" />
<item android:drawable="#drawable/musicon2" android:duration="50" />
<item android:drawable="#drawable/musicon3" android:duration="50" />
<item android:drawable="#drawable/musicon4" android:duration="50" />
<item android:drawable="#drawable/musicon5" android:duration="50" />
</animation-list>
Then set the image resource to this animation-list, and animate it:
musicEnable_ImageButton.setImageResource(R.id.sound_button);
AnimationDrawable frameAnimation = (AnimationDrawable) musicEnable_ImageButton.getBackground();
frameAnimation.start();
On API 21+ it is even easier, you can create an AnimatedStateListDrawable to wrap your animation-list (or lists). Then set android:button attribute of a RadioButton to the AnimatedStateListDrawable and watch it animate as you call setChecked().
Related
I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.
Here is the CardView XML file (Before it was inside a Relative Layout)
<androidx.cardview.widget.CardView
android:id="#+id/cardviewClassesBlock1"
android:layout_width="330dp"
android:layout_height="75dp"
android:layout_marginTop="90dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background">
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:textSize="22sp"
android:fontFamily="#font/amiko_semibold"
android:textColor="#color/white"
android:text="Block A"/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_marginStart="10dp"
android:layout_below="#+id/textviewClassesBlock1"
android:background="#drawable/rounded_corner_edittext" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="5dp"
android:textColor="#color/white"
android:text="P - 0 | T - 0 | A - 0"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
I have created a sample project for You.
First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp"
android:layout_margin="10dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
>
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:text="Block A"
android:textSize="22sp"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_below="#+id/textviewClassesBlock1"
android:layout_marginStart="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="5dp"
android:text="P - 0 | T - 0 | A - 0"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
This is basically Your CardView with small changes.
Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<Button
android:id="#+id/butAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Card"
/>
<Button
android:id="#+id/butDoSth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Do something"
/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
android:id="#+id/includedLayoutFirst"
layout="#layout/card_base"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.
Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;
public class MainActivity extends AppCompatActivity
{
private int starter = 66; //ASCII code for `B`
LinearLayoutCompat cards;
Button buttonAdd;
Button buttonDoSth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = findViewById(R.id.cards);
buttonAdd = findViewById(R.id.butAdd);
buttonDoSth = findViewById(R.id.butDoSth);
buttonAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CardView newCard = new CardView(MainActivity.this);
getLayoutInflater().inflate(R.layout.card_base, newCard);
TextView t = newCard.findViewById(R.id.textviewClassesBlock1);
String current = Character.toString((char) starter++);
t.setText("Block " + current);
newCard.setTag(current); //
cards.addView(newCard);
}
});
buttonDoSth.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
findBlockAndDoSomething("B");
}
});
}
private void findBlockAndDoSomething(String name)
{
Log.d("MyTAG", "CLICK");
for (int i = 0; i < cards.getChildCount(); i++)
{
CardView selected = (CardView) cards.getChildAt(i);
if (selected.getTag() != null && selected.getTag().toString().equals(name))
{
// do something. E.g change block name
TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
textViewClassesBlock1.setText("Block XXX");
return;
}
}
}
}
Result (starter code and with adding new CardView):
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I just started an app for a project which I wanted to have an into slider for. I got everything working except for the page dots, which do not display when the IntroSlider activity, the activity which displays all of the slides, is launched, and crashes the application when trying to go to the next slide. I don't understand what is causing the error, I would appreciate any help. Look for the comment in IntroSlider.java which specifies the line number that Android Studio says is causing the error. Thank you
IntoSlider.java:
package com.businessbrains.businessbrains.Activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.businessbrains.businessbrains.Adapters.SlidesAdapter;
import com.businessbrains.businessbrains.Internals.PreferenceManager;
import com.businessbrains.businessbrains.R;
public class IntroSlider extends AppCompatActivity implements View.OnClickListener{
private ViewPager mPager;
private int[] layouts = {R.layout.slide_welcome, R.layout.slide_account, R.layout.slide_selftest, R.layout.slide_mutliplayer};
private SlidesAdapter slidesAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private Button skipBtn, nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(new PreferenceManager(this).isSlidesEnabled()){
loadLogin();
}
if(Build.VERSION.SDK_INT >= 19){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
setContentView(R.layout.activity_intro_slider);
mPager= (ViewPager) findViewById(R.id.viewPager);
slidesAdapter = new SlidesAdapter(layouts, this);
mPager.setAdapter(slidesAdapter);
Dots_Layout = findViewById(R.id.dotsLayout);
nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(this);
skipBtn = (Button) findViewById(R.id.skipBtn);
skipBtn.setOnClickListener(this);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
createDots(i);
if(i==layouts.length-1){
nextBtn.setText("Start");
skipBtn.setVisibility(View.INVISIBLE);
}
else{
nextBtn.setText("Next");
skipBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void createDots(int current_position){
if(Dots_Layout!=null){
Dots_Layout.removeAllViews();
}
dots = new ImageView[layouts.length];
for(int i = 0; i < layouts.length; i++){
if(i==current_position){
dots[i].setImageDrawable((Drawable)ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_active_dots));
}
else{
dots[i].setImageDrawable((Drawable)(ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_inactive_dots)));
//line which is causing the error
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(4,0,4,0);
Dots_Layout.addView(dots[i], params);
}
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.nextBtn:
loadNextSlide();
break;
case R.id.skipBtn:
loadLogin();
new PreferenceManager(this).writeDisableSlides();
break;
}
}
private void loadLogin(){
startActivity(new Intent(this, LoginOptionsActivity.class));
finish();
}
private void loadNextSlide(){
int nextslide = mPager.getCurrentItem() + 1;
if(nextslide < layouts.length){
mPager.setCurrentItem(nextslide);
}
else{
loadLogin();
new PreferenceManager(this).writeDisableSlides();
}
}
}
the corresponding .xml, activity_into_slider.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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=".Activities.IntroSlider">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"
/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#android:color/white"
android:layout_marginBottom="15dp"
></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/dotsLayout"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Skip"
android:textSize="16sp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#android:color/transparent"
android:id="#+id/skipBtn"
android:layout_marginBottom="8dp"
android:textColor="#android:color/white"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:textSize="16sp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:id="#+id/nextBtn"
android:layout_marginBottom="8dp"
android:textColor="#android:color/white"
/>
</RelativeLayout>
One of the slides:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorSlide_welcome">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_welcome"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:layout_marginTop="150dp"
android:id="#+id/img"
android:tint="#android:color/black"
/>
<TextView
android:layout_width="132dp"
android:layout_height="100dp"
android:text="#string/slide1title"
android:textColor="#android:color/white"
android:textSize="30sp"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_below="#+id/img"
android:layout_marginTop="12dp"
android:id="#+id/slidetitle"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/slide1desc"
android:textColor="#android:color/white"
android:textSize="18sp"
android:gravity="center_horizontal"
android:layout_below="#+id/slidetitle"
android:layout_marginTop="10dp"
android:id="#+id/slide_desc"
android:layout_marginRight="40sp"
android:layout_marginLeft="40sp"
/>
</RelativeLayout>
The error which is being thrown:
07-11 00:30:30.253 6010-6010/com.businessbrains.businessbrains E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.businessbrains.businessbrains, PID: 6010
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.businessbrains.businessbrains.Activities.IntroSlider.createDots(IntroSlider.java:89)
at com.businessbrains.businessbrains.Activities.IntroSlider.access$000(IntroSlider.java:21)
at com.businessbrains.businessbrains.Activities.IntroSlider$1.onPageSelected(IntroSlider.java:62)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1947)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:686)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:670)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:631)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:612)
at com.businessbrains.businessbrains.Activities.IntroSlider.loadNextSlide(IntroSlider.java:118)
at com.businessbrains.businessbrains.Activities.IntroSlider.onClick(IntroSlider.java:101)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
accessory_active_dots.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="true"
android:dither="true">
<size android:height="8dp" android:width="8dp"/>
<solid android:color="#color/active_dots"/>
</shape>
accessory_inactive_dots.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="true"
android:dither="true">
<size android:height="8dp" android:width="8dp"/>
<solid android:color="#color/inactive_dots"/>
</shape>
dots = new ImageView[layouts.length]; creates an array of size layouts.length but all the elements of the array are null.
So when you invoke setImageDrawable(..) on dots[i], you are actually invoking the method setImageDrawable(..) on a null object.
Fix: initialize dots[i] (i.e., dots[i] =) with a non-null value before use. For example, do dots[i] = new ImageView() before you invoke setImageDrawable(..) on dots[i].
I'm trying to create an Android game using Android Studio.
However when I'm testing the app from the Android Studio(using my phone as a testing device), there's a white bar which appears at the bottom of the screen. If I switch to another activity and then go back to my main activity, the white bar will dissappear.
Here is my Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context="acevix.gladiators3.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/splash"
android:id="#+id/imageView"
android:scaleType="centerCrop"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:adjustViewBounds="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="140dp"
android:id="#+id/play"
android:background="#drawable/play" />
<TextView
android:text="GLADIATORS PRE-ALPHA V0.0.1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
</RelativeLayout>
And here's my styles.xml file, which I've edited in order to remove some UI:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
Activity code:
package acevix.gladiators3;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MediaPlayer splashbgmusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.play);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
playButton.setY((float) (height/4.4));
playButton.getLayoutParams().height = (int) (height / 5.14);
playButton.getLayoutParams().width = (int) (width / 3.47);
playButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d("SIZE", "Height " + view.getHeight() + ", Width: " + view.getWidth());
Intent intent = new Intent(MainActivity.this, PlayStage.class);
startActivity(intent);
}
}
);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
splashbgmusic = MediaPlayer.create(MainActivity.this, R.raw.login);
splashbgmusic.setLooping(true); // Set looping
splashbgmusic.setVolume(1.0f, 1.0f);
splashbgmusic.start();
}
#Override
protected void onPause() {
super.onPause();
splashbgmusic.stop();
}
#Override
protected void onStop() {
super.onStop();
splashbgmusic.stop();
}
#Override
public void onWindowFocusChanged(boolean hasFocas) {
super.onWindowFocusChanged(hasFocas);
View decorView = getWindow().getDecorView();
if(hasFocas) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
}
UPDATE: Apparently the problem is caused by the styles.xml file. If I change the "Theme.AppCompat.Light.NoActionBar" to "Theme.AppCompat.Light.DarkActionBar", the white bar won't appear anymore BUT when I switch between activities the blue navigation bar at the top showing the name of the game will appear for a short time and then dissappear.
And here's a youtube video which shows you exactly the problem (annotations included): https://www.youtube.com/watch?v=lEdkXZRdsu0
Try doing the following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:src="#drawable/splash"
android:id="#+id/imageView"
android:scaleType="fitXY"
/>
<!-- <ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash"
android:id="#+id/imageView"
/> --> //If above dosent work try this.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="140dp"
android:id="#+id/play"
android:background="#drawable/play" />
<TextView
android:text="GLADIATORS PRE-ALPHA V0.0.1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
</RelativeLayout>
P.S With Reference to your comments
in onCreate(...) of your activity write setContentView(R.layout.splash);
getActionBar().hide();
or
setContentView(R.layout.splash);
getSupportActionBar().hide();
to hide the actionbar
I wrote the XML for a Quiz App.
There will be (10) questions, some RadioGroup and some CheckBox, but the type of questions will not be in any order. So the 1st is radiogroup, the 2nd checkbox, the 3rd, 4th, and 5th radiogroup, the 6th and 7th checkbox, etc.
The RadioGroup obviously has only one correct answer, and the CheckBox have two or three correct answers.
I want to create a "CHECK QUIZ" button, which displays a message at the top of the scrolling quiz giving the number correct, and also displaying a large red "X" in red at the front of each wrong answer.
I am not sure where to start for the Java code in my MainActivity java file.
MainActivity.java
package com.example.android.quiztest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.TextView;
/**
* package com.example.android.quiztest;
* This app displays a radio button and checkbox quiz, and then grades the quiz, * displaying the score and identifying the incorrect answers.
**/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.android.quiztest.R.layout.activity_main);
}
}
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.quiztest.MainActivity"
android:fillViewport="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="vertical">
<EditText
android:id="#+id/name_text_view_STUDENT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/text_person_name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/label_text_view_DIRECTIONS"
style="#style/HeaderTextStyle"
android:textSize="20sp"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_directions" />
<TextView
android:id="#+id/label_text_view_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
<RadioGroup
android:id="#+id/radioGroup_1"
style="#style/HeaderTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radioButton_1a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1a"
android:textSize="#dimen/text_size_1" />
<RadioButton
android:id="#+id/radioButton_1b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1b"
android:textSize="#dimen/text_size_1" />
<RadioButton
android:id="#+id/radioButton_1c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1c"
android:textSize="#dimen/text_size_1" />
</RadioGroup>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_marginTop="25dp"
android:background="#c0c0c0" />
<TextView
android:id="#+id/label_text_view_2"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_2" />
<CheckBox
android:id="#+id/checkBox_2a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2a"
android:textSize="#dimen/text_size_1" />
<CheckBox
android:id="#+id/checkBox_2b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2b"
android:textSize="#dimen/text_size_1" />
<CheckBox
android:id="#+id/checkBox_2c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_2c"
android:textSize="#dimen/text_size_1" />
</LinearLayout>
</ScrollView>
strings.xml
<resources>
<string name="text_button_1">check answers</string>
<string name="app_name">Quiz Test</string>
<string name="text_person_name">Type student name here.</string>
<string name="text_directions">Select ALL correct answers:</string>
<string name="text_1">1) probability distribution</string>
<string name="text_1a">1a) A smooth curve indicating the frequency distribution for a discontinuous random variable.</string>
<string name="text_1b">1b) A discontinuous dot diagram showing the frequency distribution for a random variable.</string>
<string name="text_1c">1c) A smooth curve indicating the frequency distribution for a continuous random variable.</string>
<string name="text_2">2) normal distribution</string>
<string name="text_2a">2a) A smooth double-peak bell-shaped curve symmetrical about the mean.</string>
<string name="text_2b">2b) A smooth single-peak curve </string>
<string name="text_2c">3c) A bell-shaped curve symmetrical about the mean. </string>
</resources>
I updated the XML to provide the ability to mark a red X in front of the wrong answers:
file: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="false"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="vertical">
<EditText
android:id="#+id/name_textView_STUDENT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/text_person_name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView_directions"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_directions"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/dimension_1"
android:orientation="horizontal">
<TextView
android:id="#+id/incorrect_question_1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/dimension_1"
android:gravity="center"
android:text="X"
android:textColor="#ff0000"
android:textSize="30dp"
android:visibility="gone" />
<TextView
android:id="#+id/textView_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
</LinearLayout>
<RadioGroup
android:id="#+id/radioGroup_1"
style="#style/HeaderTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radioButton_1a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:textSize="#dimen/text_size_1"
android:text="#string/text_1a"
android:onClick="onClick_1a"/>
<RadioButton
android:id="#+id/radioButton_1b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1b"
android:textSize="#dimen/text_size_1"
android:onClick="onClick_2a"/>/>
<RadioButton
android:id="#+id/radioButton_1c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimension_1"
android:paddingLeft="#dimen/dimension_4"
android:paddingRight="#dimen/dimension_5"
android:text="#string/text_1c"
android:textSize="#dimen/text_size_1"
android:onClick="onClick_3a"/>
</RadioGroup>
And developed the Java grading logic for the radio groups and checkboxes:
file: MainActivity.java
package com.example.android.quiztest2;
/**
* *Below added my unique package name "com.example.android.justjava4"
*/
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
/**
* package com.example.android.justjava4;
* This app displays an order form to order coffee, and displays the information.
* quantity is a global variable
**/
public class MainActivity extends AppCompatActivity {
private RadioButton radioButton_1a, radioButton_1b, radioButton_1c, radioButton_4a, radioButton_4b, radioButton_4c,
radioButton_5a, radioButton_5b, radioButton_5c, radioButton_6a, RadioButton_6b, radioButton_6c,
radioButton_7a, radioButton_7b, radioButton_7c, radioButton_9a, radioButton_9b, radioButton_9c;
private CheckBox checkBox_2a, checkBox_2b, checkBox_2c, checkBox_3a, checkBox_3b, checkBox_3c, checkBox_8a, checkBox_8b, checkBox_8c;
int grade = 0;
public void Score(int grade) {
if (radioButton_1c.isChecked()) grade++;
if (radioButton_4c.isChecked()) grade++;
if (radioButton_5c.isChecked()) grade++;
if (radioButton_6c.isChecked()) grade++;
if (radioButton_7c.isChecked()) grade++;
if (radioButton_9c.isChecked()) grade++;
if (checkBox_2a.isChecked() && !checkBox_2b.isChecked() && checkBox_2c.isChecked()) grade++;
if (checkBox_3a.isChecked() && checkBox_3b.isChecked() && checkBox_3c.isChecked()) grade++;
if (checkBox_8a.isChecked() && !checkBox_8b.isChecked() && checkBox_8c.isChecked()) grade++;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.android.quiztest2.R.layout.activity_main);
final Context currentContext = this;
Button button_grade_quiz = (Button)
findViewById(R.id.button_grade_quiz);
button_grade_quiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answerCorrect1 = false;
TextView incorrectQuestionOne = (TextView) findViewById(R.id.incorrect_question_1);
if (!answerCorrect1) {
incorrectQuestionOne.setVisibility(View.VISIBLE);
} else {
incorrectQuestionOne.setVisibility(View.GONE);
}
}
});
}
}
Not sure how to connect the grading function to the other java methods.
Simple Answer: Add a button to your xml, and assign it an id. For example, the xml would most likely look something like this:
<Button
android:id="#+id/quiz_complete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Finish Quiz"
android:textSize="#dimen/text_size_1"
android:layout_gravity="center"/>
Then, in your MainActivity AFTER setContentView is called, you will find your button view by its id, and set an onClickListener to it. My sample code below includes a rough test that will show a Toast message when the button is clicked so that you can see the button is hooked up correctly to the listener.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context currentContext = this;
Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
Toast.makeText(currentContext, "TESTING", Toast.LENGTH_LONG).show();
}
});
}
(Note - to clarify, the bold above is to indicate that you can only reference views once they are shown - which is what is done by setContentView above. If you try to call findViewById before setContentView, you will receive a crash.)
Here is where it gets more complicated.
Without writing the whole of the solution, what I would do in order to reach your goal is to add the entirety of what you would like the quiz to look like, if the user submits the quiz with all answers wrong, in xml. I have created the xml for question 1. (I've added a horizontal LinearLayout in order to preserve the rest of your xml, but for the complexity of your view, I would recommend using a RelativeLayout)
As you can see, the visibility of the incorrect label is set to "gone". This means the view will not be seen, but also will not take up space with the parent view. "invisible" would hide the view, but its space would still be filled.
Now, when the test is submitted, we will show the incorrect answer label. In your complete solution, of course, you will evaluate whether the answer is correct or not.
XML for question one label:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/question_1_incorrect_label"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#color/red"
android:gravity="center"
android:visibility="gone"/>
<TextView
android:id="#+id/label_text_view_1"
style="#style/HeaderTextStyle"
android:layout_marginTop="#dimen/dimension_1"
android:text="#string/text_1" />
</LinearLayout>
Updated MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context currentContext = this;
Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answer1Correct = false;
//TODO: Evaluate the actual value of answer1Correct boolean.
TextView questionOneIncorrectLabel = (TextView)findViewById(R.id.question_1_incorrect_label);
if (!answer1Correct) {
questionOneIncorrectLabel.setVisibility(View.VISIBLE);
}
else {
questionOneIncorrectLabel.setVisibility(View.GONE);
}
}
});
}
Note - in colors.xml, added:
<color name="red">#FF0000</color
The rest should just be some legwork to get it working, as well as the code within MainActivity to analyze whether or not each answer is correct.
Finally, a hint to simplify your correct answer message. You can create a string constant with a placeholder for a value to be added later. For example:
<string name="text_quiz_complete_answers">You answered %d question(s) correctly.</string>
When pulling this string value from the strings.xml file, you reference it like this:
String.format(getString(R.string.text_quiz_complete_answers), 5)
With 5 just being a placeholder. Instead there should be the numerical value you calculated.
For more info on formatting strings like this, I would reference this post: Are parameters in strings.xml possible?
I have a CustomView which contains a LinearLayout that holds an EditText & another custom view element. However, when I run my app and touch the EditText it does not behave as expected (doesn't appear to receive focus & the soft keyboard doesn't open). I've tried setting duplicateParentState="true" on both the EditText & the LinearLayout. I also attached an onTouchEventListener to the EditText that calls a simple toast & the toast did show up.
Here's the code for my CustomView.
form_field.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_marginBottom="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/grey_rounded_borders">
<EditText
android:id="#+id/edit_text"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="text"
android:padding="10dp"
android:textColor="#2d6169"
android:textSize="18sp"
android:background="#color/transparent" />
<RelativeLayout
android:layout_marginStart="5dp"
android:layout_marginEnd="10dp"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<com.example.app.ValidationIcon
android:id="#+id/validation_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:ignore="ContentDescription" />
</RelativeLayout>
</LinearLayout>
FormField.java
package com.example.app;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class FormField extends LinearLayout {
private EditText editText;
private ValidationIcon validationIcon;
private Integer fieldInputType;
private String fieldInputHint;
public FormField(Context context)
{
super(context);
}
public FormField(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
TypedArray attrs = context.obtainStyledAttributes(attributeSet, R.styleable.FormField, 0, 0);
fieldInputType = attrs.getInt(
R.styleable.FormField_fieldInputType,
InputType.TYPE_TEXT_VARIATION_NORMAL
);
fieldInputHint = attrs.getString(
R.styleable.FormField_fieldInputHint
);
attrs.recycle();
inflate(getContext(), R.layout.form_field, this);
this.setFocusable(true);
this.setFocusableInTouchMode(true);
editText = (EditText)findViewById(R.id.edit_text);
editText.setInputType(fieldInputType);
editText.setHint(fieldInputHint);
editText.setFocusableInTouchMode(true);
validationIcon = (ValidationIcon)findViewById(R.id.validation_icon);
validationIcon.setValid(true);
ArrayList<View> touchables = new ArrayList<View>();
touchables.add(this);
touchables.add(editText);
addTouchables(touchables);
}
public FormField(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
}
registration_layout.xml
<RelativeLayout android:id="#+id/container"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<RelativeLayout android:id="#+id/account_details"
android:layout_marginBottom="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.app.FormField
android:id="#+id/name_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/name_field_hint" />
<com.example.app.FormField
android:id="#+id/email_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/email_field_hint" />
<com.example.app.FormField
android:id="#+id/password_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/password_field_hint" />
<com.example.app.FormField
android:id="#+id/re_password_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/re_password_field_hint" />
</RelativeLayout>
</RelativeLayout>
Min SDK Version is set at 14, target is set at 20. Any help would be greatly appreciated!
EDIT:
I got this logcat message today while testing long presses on my FormFields.
W/TextView﹕ TextView does not support text selection. Action mode cancelled.
I double checked my code and the EditText element is only ever cast as an EditText. If the EditText is being cast to a TextView that would explain my original issues but now I'm confused as to why or how it was cast as a TextView.
It looks like you are extending LinearLayout but never using it in your layout. From what you've posted, you aren't using the FormField at all and the only custom View I see is the ValidationIcon view. So hooking the touch events into EditText and ValidationIcon aren't occurring because you aren't using FormField in your layout.xml.
Rather than extending LinearLayout, why not just use the predefined methods and attributes to handle the behaviour you are trying to achieve. For example, displaying keyboard, requesting focus, and displaying hint:
<EditText
android:id="#+id/edit_text"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
**android:inputType="text"**
**android:hint="#styleable/FormField_fieldInputHint"**
android:padding="10dp"
android:textColor="#2d6169"
android:textSize="18sp"
android:background="#color/transparent" />
The keyboard should display when the edit text receives focus, if not you could programmatically do this by requesting focus and handling the IME manager call. For example, from the Activity/Fragment:
//call this from onViewCreated to grab focus and begin the flow
editText.requestFocus();
//set focus listener to handle keyboard display
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
} else {
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromWindow(myEditText.getWindowToken(), 0);
}
});
Make sure have not been setting inputType:'none' or '0X000000'
use this code for custom Edittext with title
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:foregroundGravity="right"
app:layout_anchorGravity="right">
<LinearLayout
android:orientation="vertical"
android:id="#+id/search_closed_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:background="#color/white"
android:foregroundGravity="center"
android:gravity="right">
<TextView
android:id="#+id/txt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:layout_marginStart="16dp"
android:layout_marginTop="14dp"
android:fontFamily="#font/intel"
android:foregroundGravity="center"
android:text="textview"
android:textColor="#color/title_color"
android:textSize="14dp"
android:textStyle="bold" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/lay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:clickable="true"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/edt_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/edit_txtbg"
android:fontFamily="#font/intel"
android:gravity="center|start"
android:paddingStart="24dp"
android:textColor="#color/text_color"
android:textColorHint="#color/txt_hint"
android:textSize="#dimen/text_nev"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/img_add_patient"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</FrameLayout>
CustomEditText.kt
package com.mdppractice.custom
import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.mdppractice.R
class CustomEditText(
context: Context,
attrs: AttributeSet,
) : FrameLayout(context, attrs) {
private var txt_title: TextView
private var edt_text: EditText
init {
LayoutInflater.from(context)
.inflate(R.layout.custom_view, this, true)
txt_title = findViewById(R.id.txt_title)
edt_text = findViewById(R.id.edt_text)
val a = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText)
txt_title.text = a.getString(R.styleable.CustomEditText_title)
edt_text.hint = a.getString(R.styleable.CustomEditText_hint)
when(a.getString(R.styleable.CustomEditText_inputType)) {
"number" -> edt_text.inputType = InputType.TYPE_CLASS_PHONE
"textCapSentences" -> edt_text.inputType = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
"text" -> edt_text.inputType = InputType.TYPE_CLASS_TEXT
}
a.recycle()
}
fun setmInputType(type: Int) {
edt_text.setRawInputType(InputType.TYPE_CLASS_TEXT)
setmInputType(type)
}
fun setTitle(title: Int) {
txt_title.setText(title)
}
fun set_Text(title: Int) {
edt_text.setText(title)
}
fun getTitle(): String {
return txt_title.text.toString()
}
fun get_Text(): String {
return edt_text.text.toString()
}
}
main/../attr.xml
<declare-styleable name="CustomEditText">
<attr name="title" format="string"/>
<attr name="onCenter" format="boolean"/>
<attr name="hint" format="string"/>
<attr name="maxLength" format="integer"/>
<attr name="inputType" format="string"/>
</declare-styleable>
#drawable/edit_txtbg
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/listview_background_shape">
<stroke android:width="1dp" android:color="#color/button_bg_border" />
<padding android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp" />
<corners android:radius="6dp"/>
<solid android:color="#color/button_bg" />
</shape>
use in layout
<com.mdppractice.custom.CustomEditText
android:id="#+id/edt_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="Patient ID/Phone"
android:autofillHints="#string/verified"
android:foregroundGravity="center"
android:hint="Please enter name"
app:inputType="textCapSentences"
android:textColor="#color/title_color"
android:textSize="14dp"
android:textStyle="bold" />
thanks you